準備技術:
開始實做:
新開一個Vaadin 7 專案
只實做一個UI程式展示TODO
程式如下,UI部分只用Label,TextField,Table,輸入一個字串,就加到Table。Vaadin處理Data binding的方式,是透過 Java property傳遞資料,所以TextField輸入字串後,Table設立一個Listener負責看資料變化,透過 valueChange方法,將新的資料以item加入。
package com.example.vaadintodo;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@SuppressWarnings("serial")
@Theme("vaadintodo")
public class VaadintodoUI extends UI {
int count = 0;
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = VaadintodoUI.class)
public static class Servlet extends VaadinServlet {
}
public void myLayout() {
// layout setting
VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Label display = new Label("TODO Project ");
Label show = new Label("show");
TextField input = new TextField("");
input.setImmediate(true);
show.setImmediate(true);
Table table = new Table("The TODO List TABLE");
table.setImmediate(true);
input.addValueChangeListener(
new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
show.setValue(input.getValue());
table.addItem(new Object[] { input.getValue(), -0.01f }, count);
count++;
table.setPageLength(table.size());
}
});
table.addContainerProperty("Name", String.class, null);
table.addContainerProperty("Mag", Float.class, null);
count++;
table.addItem(new Object[] { "Canopus", -0.72f }, count);
count++;
table.addItem(new Object[] { "Arcturus", -0.04f }, count);
count++;
table.addItem(new Object[] { "Alpha Centauri", -0.01f }, count);
count++;
table.setPageLength(table.size());
// Add component to layout
layout.addComponent(display);
layout.addComponent(input);
layout.addComponent(show);
layout.addComponent(table);
}
@Override
protected void init(VaadinRequest request) {
myLayout();
}
}
程式執行後,就有TODO的效果了。
參考資料
Day12 結束